/**
 * 
 */
package com.zznode.client.wlanpolling.other;

import java.io.ByteArrayInputStream;

import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Node;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.service.net.HttpCallback;
import com.zznode.client.wlanpolling.service.net.HttpException;
import com.zznode.client.wlanpolling.service.xml.XmlParserException;
import com.zznode.client.wlanpolling.service.xml.XmlXPathAdaptor;

/**
 * @author Bean
 * 故障描述Activity
 */
public class BreakdownActivity extends Activity implements HttpCallback {
	private WLANPollingApplication application;
	private EditText etFaultDesc;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.breakdown);
		
		etFaultDesc = (EditText)findViewById(R.id.faultDesc);
		
		application = (WLANPollingApplication)getApplication();
		Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
		btnSubmit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//提交故障描述
				WLANPollManager.getWLANPollManager().postBreakdownInfo(BreakdownActivity.this, 
						application.getContext().getCurrentWifi().getBSSID(),
						etFaultDesc.getEditableText().toString());
			}
		});
	}

	@Override
	public void onReceiveData(byte[] data, final HttpException exp, int tag) {
		if(exp == null) {
			XmlXPathAdaptor xpathAdaptor;
			String status = "1";
			String info = "";
			try {
				xpathAdaptor = new XmlXPathAdaptor(new ByteArrayInputStream(data));
				Node resultCode  = (Node)xpathAdaptor.evaluate("/NODE/RESULT_CODE ", XPathConstants.NODE);
				status = resultCode.getAttributes().getNamedItem("name").getNodeValue();
				info = resultCode.getTextContent();
			} catch (XmlParserException e) {
				status = "0";
				info = e.getMessage();
			}
				
			if("1".equals(status)) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(BreakdownActivity.this, "提交故障描述信息成功!", Toast.LENGTH_LONG).show();
					}
				});
			} else {
				final String infoT = info;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(BreakdownActivity.this, "提交故障描述信息失败,原因:" + infoT, Toast.LENGTH_LONG).show();
					}
				});
			}
		} else {
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					Toast.makeText(BreakdownActivity.this, "提交故障描述信息失败,原因:" + exp.getMessage(), Toast.LENGTH_LONG).show();
				}
			});
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
}
